<?php
require_once 'Zend/Db/Table/Abstract.php';
class MSA_Model_Category extends Zend_Db_Table_Abstract
{
	protected $_name = 'category';
	
	const STYLE_TREE = 1;//树状结构数组
	const STYLE_NON_TREE = 2;//非树状结构数组
	
	/**
	 * 
	 * 取出全部分类
	 * @param int $style
	 * @return array $output
	 */
	public function selectCategoryTree($style = STYLE_NON_TREE)
	{
		$query = $this->select()->where('status = 1')->order('sort ASC');
		$rows = $this->fetchAll($query);
		$rows = $rows->toArray();
		$output = array();
		$output = $this->_recursiveTree($rows);
		
		if ($style == MSA_Model_Category::STYLE_TREE) {
			return $output;
		}
		
		$output = $this->_recursiveNonTree($output);
		return $output;
	}
	
	private function _recursiveNonTree($treeData) 
	{
		$result = array();
		
		foreach ($treeData as $key=>$row) {
			$result[] = $row;
			if (!empty($row['children'])) {
				$temp = array();
				$temp = $this->_recursiveNonTree($row['children']);
				$result = array_merge($result, $temp);
			}
		}
		
		$temp = array();
		foreach ($result as $row) {
			unset($row['children']);
			$temp[] = $row;
		}
		$result = $temp;
		return $result;
	}
	
	private function _recursiveTree($data, $parent = 0, $deep = 0) 
	{
		$result = array();
		
		foreach ($data as $row) {
			if ($row['parent_id'] == $parent) {
				$row['deep'] = $deep;
				$row['children'] = $this->_recursiveTree($data, $row['id'], ($deep + 1));
				if (empty($row['children'])) {
					$row['is_leaf'] = true;
				}
				else {
					$row['is_leaf'] = false;
				}
				$result[] = $row;
			}
		}
		return $result;
	}
}